package cn.bmbanjia.zebra2024.aliyuncloud.rocketmq.producer;

import cn.bmbanjia.zebra2024.aliyuncloud.rocketmq.consumer.BmbjClewDelayPushConsumer;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.apache.rocketmq.client.apis.producer.SendReceipt;

import java.time.Duration;

@Slf4j
public class BmbjProducerDelayMessage {

    private static final ClientServiceProvider provider = ClientServiceProvider.loadService();

    private static Producer producer;

    static {
        try {
            producer = ProducerSingleton.getInstance(BmbjClewDelayPushConsumer.topics);
        } catch (ClientException e) {
            log.error("e: ", e);
        }
    }

    public static void sendBmbjClewDelayMessage(byte[] body) {
        Duration duration = Duration.ofMinutes(5);
        Message message = provider.newMessageBuilder()
                .setTopic(BmbjClewDelayPushConsumer.topics[0])
                .setTag(BmbjClewDelayPushConsumer.tag)
                .setKeys(IdUtil.fastSimpleUUID())
                .setDeliveryTimestamp(System.currentTimeMillis() + duration.toMillis())
                .setBody(body)
                .build();
        try {
            SendReceipt sendReceipt = producer.send(message);
            log.info("Send message successfully, messageId={}", sendReceipt.getMessageId());
        } catch (ClientException e) {
            log.error("Failed to send message", e);
        }

    }

}
